<template>
	<view>
		<form>
			<view class="cu-form-group">
				<view class="title">姓名</view>
				<input placeholder="请输入姓名" v-model="form.name" name="input"></input>
			</view>
			<view class="cu-form-group">
				<view class="title">电话</view>
				<input placeholder="请输入电话" v-model="form.phone" name="input"></input>
			</view>
			<view class="cu-form-group">
				<textarea maxlength="-1" v-model="form.address" placeholder="请输入详细地址"></textarea>
			</view>
			<view class="cu-form-group">
				<view class="title">默认</view>
				<switch class='red' @change="changeSwitch" :class="isSwitch?'checked':''" :checked="isSwitch"
					color="#e54d42"></switch>
			</view>


		</form>
		<view class="padding">
			<view @click="onSubmit" class="cu-btn block bg-green lg">
				保存
			</view>
		</view>
	</view>
</template>

<script>
	import AddressApi from "@/api/address"
	export default {
		data() {
			return {
				form: {
					id: 0,
					name: '',
					phone: '',
					address: '',
					status: 0,
				},
				isSwitch: false
			}
		},
		onLoad: function(option) {
			if (option.id) {
				this.loadData(option.id);
			}
		},
		methods: {
			loadData(id) {
				AddressApi.get(id).then((res) => {
					this.form = res
					this.isSwitch = this.form.status==1
				})
			},
			onSubmit() {
				let msg = '';
				if (!this.form.name) {
					msg = "请输入姓名"
				} else if (!this.form.phone) {
					msg = "请输入电话"
				} else if (!this.form.address) {
					msg = "请输入详细地址"
				}
				if (msg) {
					uni.showToast({
						title: msg,
						icon: 'none'
					});
					return;
				}
				if (this.form.id) {
					AddressApi.update(this.form).then(() => {
						this.onSuccess()
					})
				} else {
					AddressApi.add(this.form).then(() => {
						this.onSuccess()
					})
				}
			},
			onSuccess(){
				uni.showToast({
					title: "保存成功",
				});
				uni.navigateBack({
				    delta: 1
				});
			},
			changeSwitch(e) {
				this.isSwitch = e.detail.value;
				this.form.status = this.isSwitch ? 1 : 0
			},
		}
	}
</script>

<style>

</style>
